package com.sap.health.tracker;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
import com.sap.health.tracker.R;
import com.sap.health.tracker.library.Utils;

/*
 * This class is used to generate ids and handle push notifications from Google.
 */
public class GCMIntentService extends GCMBaseIntentService{

	public GCMIntentService(){
		super(Utils.GCMSenderId);
	}
	
	@Override
	protected void onError(Context context, String regId) {	
		Log.e("", "error registration id : " + regId);
		Utils.registrationError = regId;	// Pass the message to Utils class.
	}
	
	@Override
	protected void onMessage(Context context, Intent intent) {
		//when notification is received, handle the message.
		handleMessage(context, intent);
	}
	
	@Override
	 protected void onRegistered(Context context, String regId) {
		Log.e("", "registration id : " + regId);
		handleRegistration(context, regId); 	// handle registration id.
	 }
	
	@Override
	 protected void onUnregistered(Context context, String regId) {
	 // TODO add method that unregisters the device from Google.
	 }
	
	/*
	 * This function splits the notification up and passes it to the 
	 * notifications displayer.
	 */
	private void handleMessage(Context context, Intent intent) {
		// splits up the notification.
		Utils.notiMsg = intent.getStringExtra("msg");
		Utils.notiTitle = intent.getStringExtra("title");
		Utils.notiType = intent.getStringExtra("type");
		Utils.notiTime = intent.getStringExtra("time");
		// run the function that show the notification.
		activateNotifications();
	}
	
	/*
	 *  This function displays the notification.
	 *  
	 *  @SuppressLint("NewApi"): Since this is designed for backwards and 
	 *  forwards compatibility, API14 doesn't recognise "rich notifications". 
	 *  Therefore we will be using the old and new notification system.
	 *  
	 *  @SuppressWarnings("deprecation"): Since the API target is 16, the 
	 *  old notification system is now deprecated.
	 */
    @SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	public void activateNotifications (){
		// get the current version of the OS
		int currentapiVersion = android.os.Build.VERSION.SDK_INT;
		// Check the versions.
		if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN){
			// This section is for Jelly Bean (API 16) and above.
			Bitmap bm = Bitmap.createScaledBitmap(BitmapFactory.decodeResource
					(getResources(), R.drawable.avatar),
						getResources().getDimensionPixelSize
							(android.R.dimen.notification_large_icon_width),
								getResources().getDimensionPixelSize
				(android.R.dimen.notification_large_icon_height),true);
			// When a notification is clicked, go to main class.
			Intent intent = new Intent(this, Main.class);
			PendingIntent pendingIntent = PendingIntent.getActivity(this, 01, 
					intent, Intent.FLAG_ACTIVITY_CLEAR_TASK);
			Notification.Builder builder = new Notification.Builder(getApplicationContext());
			// Title for the notification.
			builder.setContentTitle("Health Tracker");
			// Message to display.
			builder.setContentText(Utils.notiMsg);				
			builder.setSubText(Utils.notiTime);
			builder.setContentIntent(pendingIntent);
			builder.setTicker("Health Tracker Notification");
			builder.setSmallIcon(R.drawable.ic_launcher);
			builder.setLargeIcon(bm);
			builder.setAutoCancel(true);
			builder.setPriority(0);
			Notification notification = builder.build();
			NotificationManager notificationManger =
			(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			notificationManger.notify(01, notification);
		} else{
		    // for phones running an SDK before Jelly Bean (APKI16)	
			int icon = R.drawable.ic_launcher;
	        long when = System.currentTimeMillis();
	        NotificationManager notificationManager = (NotificationManager)
	                this.getSystemService(Context.NOTIFICATION_SERVICE);
			Notification notification = new Notification(icon, Utils.notiMsg, 
	        		when);	 
	        String title = this.getString(R.string.app_name);	 
	        Intent notificationIntent = new Intent(this, Main.class);
	        // set intent so it does not start a new activity
	        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
	                Intent.FLAG_ACTIVITY_SINGLE_TOP);
	        PendingIntent intent =
	                PendingIntent.getActivity(this, 0, notificationIntent, 0);
	        notification.setLatestEventInfo(this, title, Utils.notiMsg, intent);
	        notification.flags |= Notification.FLAG_AUTO_CANCEL;	 
	        // Play default notification sound
	        notification.defaults |= Notification.DEFAULT_SOUND;
	        // Vibrate if vibrate is enabled
	        notification.defaults |= Notification.DEFAULT_VIBRATE;
	        notificationManager.notify(0, notification);    
		}
    }
	
    /*
     * Passes the reg id to the Utils class.
     */
    private void handleRegistration(Context context, String regId) {
    	Utils.registrationId = regId;
		Log.e("", "registration id : "+regId);
	} 
}
